package com.xxl.rpc.sample.server.conf;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xxl.rpc.remoting.invoker.XxlRpcInvokerFactory;
import com.xxl.rpc.remoting.net.NetEnum;
import com.xxl.rpc.remoting.net.impl.jetty.server.JettyServerHandler;
import com.xxl.rpc.remoting.provider.XxlRpcProviderFactory;
import com.xxl.rpc.sample.api.DemoService;
import com.xxl.rpc.serialize.Serializer;

/**
 * base quartz scheduler util <br/>
 * 定时任务工具类，在启动中做很多事
 * 
 * @author xuxueli 2015-12-19 16:13:53
 */
public final class XxlJobDynamicScheduler {
	
	private static final Logger logger = LoggerFactory.getLogger(XxlJobDynamicScheduler.class);

	/**
	 * 启动
	 * 
	 * @throws Exception
	 */
	public void start() throws Exception {
		// admin-server
		// admin的服务启动:让执行器可以调用调度中心的接口
		initRpcProvider();

		logger.info(">>>>>>>>> init xxl-job admin success.");
	}

	/**
	 * 停止
	 * 
	 * @throws Exception
	 */
	public void destroy() throws Exception {
		// admin-server
		stopRpcProvider();
	}

	// ------ admin rpc provider (no server version) ----调度中心服务(RPC的服务提供者,被执行器调用)---TODO------------------
	private static JettyServerHandler jettyServerHandler;

	/**
	 * ----- TODO ----(与调度中心不同，这边内置一个jetty服务器,共用一个web端口server.port)
	 */
	private void initRpcProvider() {
		// init
		XxlRpcProviderFactory xxlRpcProviderFactory = new XxlRpcProviderFactory();
		
		xxlRpcProviderFactory.initConfig(NetEnum.JETTY, Serializer.SerializeEnum.HESSIAN.getSerializer(), null, 0,
				"", null, null);

		// add services:增加调度中心服务到PRC
		xxlRpcProviderFactory.addService(DemoService.class.getName(), null,
				XxlJobAdminConfig.getAdminConfig().getDemoService());

		// jetty handler,以jetty的方式启动
		jettyServerHandler = new JettyServerHandler(xxlRpcProviderFactory);
	}

	/**
	 * 停止
	 * @throws Exception
	 */
	private void stopRpcProvider() throws Exception {
		new XxlRpcInvokerFactory().stop();
	}

	/**
	 * 远程执行的时候要调用的
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public static void invokeAdminService(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		jettyServerHandler.handle(null, new Request(null, null), request, response);
	}



}